import json
import pymongo
import time
from django.shortcuts import render
from django.shortcuts import redirect
from django.http import HttpResponse
from bson import json_util
from django.contrib.auth.decorators import login_required
from django.contrib.auth.decorators import permission_required
from django.contrib.auth import login,authenticate

#配置数据库连接
myclient = pymongo.MongoClient("mongodb://localhost:27017/")
mydb = myclient["test3"]

mycoldl = mydb["dlhistory"] #下载的历史记录

def api1(request):
    mycol1.insert_one(json.loads(request.body.decode('utf-8')))
    #mycol1.insert_one(json.loads(request.POST.get('data'))) #json.loads()函数是将json格式数据转换为字典（可以这么理解，json.loads()函数是将字符串转化为字典）
    return HttpResponse({})

def api2(request):
    mycol2.insert_one(json.loads(request.body.decode('utf-8')))
    #mycol2.insert_one(json.loads(request.POST.get('data')))  # json.loads()函数是将json格式数据转换为字典（可以这么理解，json.loads()函数是将字符串转化为字典）
    return HttpResponse({})

def api4(request):
    mycol4.insert_one(json.loads(request.body.decode('utf-8')))
    #mycol4.insert_one(json.loads(request.POST.get('data')))  # json.loads()函数是将json格式数据转换为字典（可以这么理解，json.loads()函数是将字符串转化为字典）
    return HttpResponse({})

def api5(request):
    mycol5.insert_one(json.loads(request.body.decode('utf-8')))
    #mycol5.insert_one(json.loads(request.POST.get('data')))  # json.loads()函数是将json格式数据转换为字典（可以这么理解，json.loads()函数是将字符串转化为字典）
    return HttpResponse({})

def api6(request):
    mycol6.insert_one(json.loads(request.body.decode('utf-8')))
    #mycol6.insert_one(json.loads(request.POST.get('data')))  # json.loads()函数是将json格式数据转换为字典（可以这么理解，json.loads()函数是将字符串转化为字典）
    return HttpResponse({})

def api7(request):  # 检查用户名和密码，判断用户是否有权限参加问卷调查
    if request.method == 'POST':
        user = authenticate(request, username=request.POST.get('username'), password=request.POST.get('password'))
        if user:
            login(request,user)
            return HttpResponse(1)
        else:
            return HttpResponse(0)
    else:
        return HttpResponse(0)

 # 0.1湖南省问卷记录选择页面

#根据前端url传来的数据，判断当前问卷类别，返回相应的问卷与草稿箱数据库以及查询信息
def getMycol(no):
    if no == 'no1':
        return {
            'mycol':mydb["questionnaire1"],  # 存储脑出血患者调查问卷
            'mycol1':mydb["questionnaire11"],  # 草稿箱中的脑出血患者调查问卷存储
            'message': {'_id': 1, '姓名': 1, '性别': 1, '出生日期': 1, '身份证号码': 1},
            'wen':'wenjuan1',

        }
    elif no == 'no2':
        return {
            'mycol':mydb["questionnaire2"],  # 存储健康人群调查问卷
            'mycol1':mydb["questionnaire12"], # 草稿箱中的健康人群调查问卷存储
            'message': {'_id': 1, '姓名': 1, '性别': 1, '出生日期': 1, '身份证号码': 1},
            'wen':'wenjuan2',
        }
    elif no == 'no4':
        return {
            'mycol':mydb["questionnaire4"],  # 存储健康人群调查问卷(体检中心)
            'mycol1':mydb["questionnaire14"],  # 草稿箱中的健康人群调查问卷(体检中心)存储
            'message': {'_id': 1, '姓名': 1, '性别': 1, '出生日期': 1, '身份证号码': 1},
            'wen':'wenjuan4',
        }
    elif no == 'no5':
        return {
            'mycol':mydb["questionnaire5"],  # 存储脑出血患者调查问卷(医院)
            'mycol1':mydb["questionnaire15"],  # 草稿箱中的脑出血患者调查问卷(医院)存储
            'message': {'_id': 1, '姓名': 1, '性别': 1, '出生日期': 1, '身份证号码': 1},
            'wen':'wenjuan5',
        }
    elif no == 'no6':
        return {
            'mycol':mydb["questionnaire6"], # 存储随访问卷
            'mycol1':mydb["questionnaire16"],  # 草稿箱中的随访问卷存储
            'message': {'_id': 1, '填表人签名': 1, '身份证号码': 1, '填表人联系电话': 1},
            'wen':'wenjuan6',
        }
    elif no == 'no7':
        return {
            'mycol':mydb["questionnaire7"],  # 存储入户筛查表
            'mycol1':mydb["questionnaire17"],  # 草稿箱中的入户筛查表存储
            'message': {'_id': 1, '姓名': 1, '性别': 1, '年龄': 1},
            'wen':'wenjuan7',
        }
    elif no == 'no8':
        return {
            'mycol':mydb["questionnaire8"], # 存储随访问卷
            'mycol1':mydb["questionnaire18"],  # 草稿箱中的随访问卷存储
            'message': {'_id': 1, '填表人签名': 1, '身份证号码': 1, '填表人联系电话': 1},
            'wen':'wenjuan8',
        }
    elif no == 'no9':
        return {
            'mycol':mydb["questionnaire9"], # 存储随访问卷
            'mycol1':mydb["questionnaire19"],  # 草稿箱中的随访问卷存储
            'message': {'_id': 1, '填表人签名': 1, '身份证号码': 1, '填表人联系电话': 1},
            'wen':'wenjuan9',
        }
    elif no == 'no10':
        return {
            'mycol': mydb["questionnaire10"],  # 存储入户筛查表
            'mycol1': mydb["questionnaire110"],  # 草稿箱中的入户筛查表存储
            'message': {'_id': 1, '填表人签名': 1, '身份证号码': 1, '填表人联系电话': 1},
            'wen': 'wenjuan10',
        }
    else:
        return {
            'mycol': mydb["questionnaire011"],  # 存储街道乡镇级调查单位基本信息采集表
            'mycol1': mydb["questionnaire111"],  # 草稿箱中的街道乡镇级调查单位基本信息采集表
            'message': {'_id': 1, '填表人签名': 1, '填表人联系电话': 1, '填表人填写日期': 1},
            'wen': 'wenjuan11',
        }

#判断省各省名称
def getProvince(province):
    if province == 'hunan':
        return '湖南省'
    elif province == 'hubei':
        return '湖北省'
    elif province == 'henan':
        return '河南省'
    elif province == 'anhui':
        return '安徽省'
    else:
        return '江西省'

        
@login_required
def wenjuan_index(request,province):

    return render(request, "wenjuan/"+province+"/index.html")

#各省各类问卷记录页面
@login_required
def wenjuan(request,province,no):
    # 从json文件中读取json数据
    # file_path = "D:/Project/ncx/Ncx-Management-System/Ques/static/json/wenjuan1.json"
    my = getMycol(no)
    wen = my['wen']
    file_path = "D:/Project/ncx/Ncx-Management-System/Ques/static/json/"+wen+".json"
    with open(file_path, 'r', encoding='UTF-8') as f:
        wenjuan_content = json.load(f)

    return render(request, 'wenjuan/'+province+'/'+wen+'.html', {"excelTitle": json_util.dumps(list(wenjuan_content))})

#各省问卷处理
@login_required
def wenjuan_solve(request,province,no):
    page = request.POST.get("page")  # 取得当前页数，注意这是jqgrid自身的参数
    rows = request.POST.get("rows")  # 取得每页显示行数，注意这是jqgrid自身的参数
    my = getMycol(no)
    mycol = my['mycol']
    message = my['message']
    province1 = getProvince(province)
    questionnaire = []

    totalRecord = mycol.find({"所在的省": province1}).count()  # 总记录数(应根据数据库取得,在此只是模拟)
     # 分页查询
    for x in mycol.find({"所在的省": province1}, message).skip((int(page) - 1) * int(rows)).limit(int(rows)):
        x['表格编号'] = x['_id']
        if no != 'no7' and '身份证号码' in x.keys():
            x['身份证号码'] = x['身份证号码'][0:13]+'****'
        questionnaire.append(x)


    if totalRecord % int(rows) == 0:  # 计算总页数
        totalPage = int(totalRecord / int(rows))
    else:
        totalPage = int(totalRecord / int(rows)) + 1


    # 构造jqGrid接受的json数据格式
    json = {
        "page": page,
        "total": totalPage,
        "records": totalRecord,
        "rows": questionnaire
    }

    return HttpResponse(json_util.dumps(json))  # answer的第一条记录为question

#湖南专用问卷处理
@login_required
def wenjuan_hunan_solve(request,no):
    page = request.POST.get("page")  # 取得当前页数，注意这是jqgrid自身的参数
    rows = request.POST.get("rows")  # 取得每页显示行数，注意这是jqgrid自身的参数
    my = getMycol(no)
    mycol = my['mycol']
    message = my['message']
    questionnaire = []

    totalRecord = mycol.find({}).count()  # 总记录数(应根据数据库取得,在此只是模拟)
     # 分页查询
    for x in mycol.find({}, message).skip((int(page) - 1) * int(rows)).limit(int(rows)):
        x['表格编号'] = x['_id']
        if no != 'no7' and '身份证号码' in x.keys():
            x['身份证号码'] = x['身份证号码'][0:13]+'****'
        questionnaire.append(x)


    if totalRecord % int(rows) == 0:  # 计算总页数
        totalPage = int(totalRecord / int(rows))
    else:
        totalPage = int(totalRecord / int(rows)) + 1


    # 构造jqGrid接受的json数据格式
    json = {
        "page": page,
        "total": totalPage,
        "records": totalRecord,
        "rows": questionnaire
    }

    return HttpResponse(json_util.dumps(json))  # answer的第一条记录为question
# 街道乡镇级调查单位基本信息采集表记录数据请求处理
@login_required
def wenjuan_hunan_solve_jd(request):  # 脑出血患者调查手册分页查询
    my = getMycol("no11")
    mycol = my['mycol']
    page = request.POST.get("page")  # 取得当前页数，注意这是jqgrid自身的参数
    rows = request.POST.get("rows")  # 取得每页显示行数，注意这是jqgrid自身的参数
    message = my['message']
    questionnaire = []
    print("街道")
    postData = request.POST.get("postData")
    postDatas = str(postData).split()

    if not postData:
        totalRecord = mycol.find({}).count()  # 总记录数(应根据数据库取得,在此只是模拟)
        for x in mycol.find({}, message).skip((int(page) - 1) * int(rows)).limit(int(rows)):
            x['填表人联系电话'] = x['填表人联系电话'][0:7] + '****'
            questionnaire.append(x)
    else:
        conditions = {}
        condition = [{"$or": [{"_id": {'$regex': postDatas[0]}},
                              {"填表人签名": {'$regex': postDatas[0]}},
                              {"填表人联系电话": {'$regex': postDatas[0]}},
                              {"填表人填写日期": {'$regex': postDatas[0]}}]}]
        for p in postDatas[1:]:
            new_condition = {"$or": [{"_id": {'$regex': p}},
                                     {"填表人签名": {'$regex': p}},
                                     {"填表人联系电话": {'$regex': p}},
                                     {"填表人填写日期": {'$regex': p}}]}
            condition.append(new_condition)
        conditions.update({"$and": condition})
        totalRecord = mycol.find(conditions).count()  # 总记录数(应根据数据库取得,在此只是模拟)
        for x in mycol.find(conditions, message).skip(
                (int(page) - 1) * int(rows)).limit(int(rows)):
            x['填表人联系电话'] = x['填表人联系电话'][0:7] + '****'
            questionnaire.append(x)

    if totalRecord % int(rows) == 0:  # 计算总页数
        totalPage = int(totalRecord / int(rows))
    else:
        totalPage = int(totalRecord / int(rows)) + 1

    # 构造jqGrid接受的json数据格式
    json = {
        "page": page,
        "total": totalPage,
        "records": totalRecord,
        "rows": questionnaire
    }

    return HttpResponse(json_util.dumps(json))  # answer的第一条记录为question
# 脑出血导出
@login_required
def ExportWenjuan(request, user, no):
    my = getMycol(no)
    mycol = my['mycol']
    wen = my['wen']
    print('测试成功1')
    answer = []
    # print(request.POST)  # 输出被django处理过的数据形式
    selectRaw = request.POST.get('selectRaw')  # 获取选择的行的编号
    selectRaw = selectRaw.split(",")
    tj = selectRaw[:-1]  # 此处获得的是_id
    # 从json文件中读取json数据
    file_path = "D:/Project/ncx/Ncx-Management-System/Ques/static/json/"+wen+".json"
    with open(file_path, 'r', encoding='UTF-8') as f:
        wenjuan_content = json.load(f)
        print(wenjuan_content)

    for id in tj:
        for x in mycol.find({"_id": id }):

            # {**excelTitle,**x}:Python3中两字典的合并与更新,使得导出问卷excel的表头是一致的,同时把调查问卷json的所有value都转换成字符串，这样就能保证导出excel没有数据缺失
            # answer.append(list({**wenjuan5_content,**x}.values()))
            answer.append([str(i) for i in list({**wenjuan_content, **x}.values())])

    mycoldl.insert({"问卷记录": no, "用户": user, "条数": len(tj), "具体信息": selectRaw, "时间": time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time()))}) #使用dlhistory存储用户下载历史
    return HttpResponse(json_util.dumps(answer))  # answer的第一条记录为question



@login_required
def DelWenjuan1(request):
    answer = []
    selectRaw = request.POST.get('selectRaw')  # 获取选择的行的编号
    selectRaw = selectRaw.split(",")
    tj = selectRaw[:-1]

    for id in tj:
        mycol1.delete_one({"患者身份证号码": id})

    for x in mycol1.find():
        answer.append(list(x.values()))

    return HttpResponse(json_util.dumps(answer))  # 验证删除是否成功


@login_required
def DelWenjuan2(request):
    answer = []
    selectRaw = request.POST.get('selectRaw')  # 获取选择的行的编号
    selectRaw = selectRaw.split(",")
    tj = selectRaw[:-1]

    for id in tj:
        mycol2.delete_one({"身份证号码": id})

    for x in mycol2.find():
        answer.append(list(x.values()))

    return HttpResponse(json_util.dumps(answer))  # 验证删除是否成功


@login_required
def DelWenjuan4(request):
    answer = []
    selectRaw = request.POST.get('selectRaw')  # 获取选择的行的编号
    selectRaw = selectRaw.split(",")
    tj = selectRaw[:-1]

    for id in tj:
        mycol4.delete_one({"身份证号码": id})

    for x in mycol4.find():
        answer.append(list(x.values()))

    return HttpResponse(json_util.dumps(answer))  # 验证删除是否成功

@login_required
def DelWenjuan5(request): #删除基线脑出血患者问卷（医院）中的调查记录
    answer = []
    selectRaw = request.POST.get('selectRaw')  # 获取选择的行的编号
    selectRaw = selectRaw.split(",")
    tj = selectRaw[:-1]

    for id in tj:
        mycol5.delete_one({"患者身份证号码":id})

    for x in mycol5.find():
        answer.append(list(x.values()))

    return HttpResponse(json_util.dumps(answer))  # 验证删除是否成功

@login_required
def DelWenjuan6(request):
    answer = []
    selectRaw = request.POST.get('selectRaw')  # 获取选择的行的编号
    selectRaw = selectRaw.split(",")
    tj = selectRaw[:-1]

    for id in tj:
        mycol6.delete_one({"身份证号码":id})

    for x in mycol6.find():
        answer.append(list(x.values()))

    return HttpResponse(json_util.dumps(answer))  # 验证删除是否成功


@login_required
def DelWenjuan7(request):
    answer = []
    selectRaw = request.POST.get('selectRaw')  # 获取选择的行的编号
    selectRaw = selectRaw.split(",")
    tj = selectRaw[:-1]

    for id in tj:
        mycol7.delete_one({"身份证号码":id})

    for x in mycol7.find():
        answer.append(list(x.values()))

    return HttpResponse(json_util.dumps(answer))  # 验证删除是否成功

@login_required
def DelWenjuan8(request):
    answer = []
    selectRaw = request.POST.get('selectRaw')  # 获取选择的行的编号
    selectRaw = selectRaw.split(",")
    tj = selectRaw[:-1]

    for id in tj:
        mycol8.delete_one({"身份证号码":id})

    for x in mycol8.find():
        answer.append(list(x.values()))

    return HttpResponse(json_util.dumps(answer))  # 验证删除是否成功

@login_required
def DelWenjuan9(request):
    answer = []
    selectRaw = request.POST.get('selectRaw')  # 获取选择的行的编号
    selectRaw = selectRaw.split(",")
    tj = selectRaw[:-1]

    for id in tj:
        mycol9.delete_one({"身份证号码":id})

    for x in mycol9.find():
        answer.append(list(x.values()))

    return HttpResponse(json_util.dumps(answer))  # 验证删除是否成功

@login_required
def DelWenjuan10(request):
    answer = []
    selectRaw = request.POST.get('selectRaw')  # 获取选择的行的编号
    selectRaw = selectRaw.split(",")
    tj = selectRaw[:-1]

    for id in tj:
        mycol10.delete_one({"身份证号码":id})

    for x in mycol10.find():
        answer.append(list(x.values()))

    return HttpResponse(json_util.dumps(answer))  # 验证删除是否成功